import { MockMethod } from 'vite-plugin-mock';
import { mock } from 'mockjs';
import { ResultBean } from '@/api/user';

// 科室数据
const deptList = [
  { id: 1, name: '办公室' },
  { id: 2, name: '政治处' },
  { id: 3, name: '警务督察处' },
  { id: 4, name: '法制处' },
  { id: 5, name: '刑侦支队' },
  { id: 6, name: '治安支队' },
  { id: 7, name: '交警支队' },
  { id: 8, name: '特警支队' }
];

// 组织架构数据
const orgList = [
  {
    id: 1,
    name: '监狱管理局',
    parentId: null,
    children: [
      {
        id: 2,
        name: '提篮桥监狱',
        parentId: 1,
        children: []
      },
      {
        id: 3,
        name: '新提篮桥',
        parentId: 1,
        children: []
      },
      {
        id: 4,
        name: '五角场监狱',
        parentId: 1,
        children: []
      },
      {
        id: 5,
        name: '周浦监狱',
        parentId: 1,
        children: []
      },
      {
        id: 6,
        name: '北新泾监狱',
        parentId: 1,
        children: []
      },
      {
        id: 7,
        name: '白茅岭',
        parentId: 1,
        children: []
      },
      {
        id: 8,
        name: '军天湖',
        parentId: 1,
        children: []
      },
      {
        id: 9,
        name: '四岔河',
        parentId: 1,
        children: []
      },
      {
        id: 10,
        name: '吴家洼',
        parentId: 1,
        children: []
      },
      {
        id: 11,
        name: '未成年犯管教所',
        parentId: 1,
        children: []
      },
      {
        id: 12,
        name: '青浦监狱',
        parentId: 1,
        children: []
      },
      {
        id: 13,
        name: '女子监狱',
        parentId: 1,
        children: []
      },
      {
        id: 14,
        name: '新收犯监狱',
        parentId: 1,
        children: []
      },
      {
        id: 15,
        name: '宝山监狱',
        parentId: 1,
        children: []
      },
      {
        id: 16,
        name: '南汇监狱',
        parentId: 1,
        children: []
      },
      {
        id: 17,
        name: '监狱总医院',
        parentId: 1,
        children: []
      },
      {
        id: 18,
        name: '司法警校',
        parentId: 1,
        children: []
      },
      {
        id: 19,
        name: '农推站',
        parentId: 1,
        children: []
      },
      {
        id: 20,
        name: '夏阳关押所',
        parentId: 1,
        children: []
      }
    ]
  }
];

// 用户数据
const userList = mock({
  'list|20': [
    {
      'userId|+1': 1,
      name: '@cname',
      'iphone|1': ['13800138000', '13900139000', '13700137000', '13600136000'],
      'role|1': [1, 2, 3],
      'policeNum|1': ['001', '002', '003', '004', '005', '006', '007', '008'],
      'group|1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
      'dept|1': [1, 2, 3, 4, 5, 6, 7, 8],
      createTime: '@datetime',
      updateTime: '@datetime'
    }
  ]
});

// 添加admin用户
userList.list.unshift({
  userId: 0,
  name: 'admin',
  iphone: '13800000000',
  role: 1,
  policeNum: 'admin001',
  group: 1,
  dept: 1,
  createTime: Date.now(),
  updateTime: Date.now()
});

let nextUserId = 6;

// 创建成功响应
const createSuccessResponse = <T>(data: T, message = '操作成功'): ResultBean<T> => ({
  code: 200,
  message,
  data
});

// 创建错误响应
const createErrorResponse = (message = '操作失败'): ResultBean<null> => ({
  code: 500,
  message,
  data: null
});

export default [
  // 获取用户列表
  {
    url: '/api/user/query',
    method: 'post',
    response: ({ body }) => {
      const { pageNo = 1, pageSize = 10, name, policeNum, role, group, dept } = body;

      let filteredList = userList.list;

      // 根据搜索条件过滤
      if (name) {
        filteredList = filteredList.filter(user => user.name.includes(name));
      }
      if (policeNum) {
        filteredList = filteredList.filter(user => user.policeNum.includes(policeNum));
      }
      if (role) {
        filteredList = filteredList.filter(user => user.role === parseInt(role));
      }
      if (group) {
        filteredList = filteredList.filter(user => user.group === parseInt(group));
      }
      if (dept) {
        filteredList = filteredList.filter(user => user.dept === parseInt(dept));
      }

      const start = (pageNo - 1) * pageSize;
      const end = start + pageSize;
      const list = filteredList.slice(start, end);

      return {
        code: 200,
        message: 'success',
        data: {
          rows: list,
          page: {
            pageNo: pageNo,
            pageSize: pageSize,
            totalRow: filteredList.length
          }
        }
      };
    }
  },

  // 获取用户详情
  {
    url: '/api/user/:id',
    method: 'get',
    response: ({ params }) => {
      const { id } = params;
      const user = userList.list.find(item => item.userId === parseInt(id));

      if (user) {
        return {
          code: 200,
          message: 'success',
          data: user
        };
      } else {
        return {
          code: 404,
          message: '用户不存在',
          data: null
        };
      }
    }
  },

  // 创建用户
  {
    url: '/api/user',
    method: 'post',
    response: ({ body }) => {
      const { name, iphone, role, policeNum, group, dept } = body;

      // 检查警号是否已存在
      if (userList.list.some(u => u.policeNum === policeNum)) {
        return createErrorResponse('警号已存在');
      }

      // 检查手机号是否已存在
      if (userList.list.some(u => u.iphone === iphone)) {
        return createErrorResponse('手机号已存在');
      }

      const newUser = {
        userId: nextUserId++,
        name,
        iphone,
        role,
        policeNum,
        group,
        dept,
        createTime: Date.now(),
        updateTime: Date.now()
      };

      userList.list.push(newUser);
      return createSuccessResponse(newUser, '创建成功');
    }
  },

  // 更新用户
  {
    url: '/api/user/:id',
    method: 'put',
    response: ({ params, body }) => {
      const { id } = params;
      const index = userList.list.findIndex(item => item.userId === parseInt(id));

      if (index !== -1) {
        userList.list[index] = {
          ...userList.list[index],
          ...body,
          updateTime: Date.now()
        };

        return createSuccessResponse(userList.list[index], '更新成功');
      } else {
        return createErrorResponse('用户不存在');
      }
    }
  },

  // 删除用户
  {
    url: '/api/user/:id',
    method: 'delete',
    response: ({ params }) => {
      const { id } = params;
      const index = userList.list.findIndex(item => item.userId === parseInt(id));

      if (index !== -1) {
        userList.list.splice(index, 1);
        return createSuccessResponse(null, '删除成功');
      } else {
        return createErrorResponse('用户不存在');
      }
    }
  },

  // 批量删除用户
  {
    url: '/api/user/batch-delete',
    method: 'post',
    response: ({ body }) => {
      const { userIds } = body;

      userIds.forEach(userId => {
        const index = userList.list.findIndex(item => item.userId === userId);
        if (index !== -1) {
          userList.list.splice(index, 1);
        }
      });

      return createSuccessResponse(null, '批量删除成功');
    }
  },

  // 获取科室列表
  {
    url: '/api/dept/list',
    method: 'get',
    response: () => {
      return {
        code: 200,
        message: 'success',
        data: deptList
      };
    }
  },

  // 获取组织架构列表
  {
    url: '/api/org/list',
    method: 'get',
    response: () => {
      return {
        code: 200,
        message: 'success',
        data: orgList
      };
    }
  },

  // 验证警号是否重复
  {
    url: '/api/user/validUserByPoliceNum',
    method: 'get',
    response: ({ query }) => {
      const { policeNum, userId } = query;

      // 检查是否存在相同警号（排除当前编辑的用户）
      const existingUser = userList.list.find(
        user => user.policeNum === policeNum && (!userId || user.userId !== parseInt(userId as string))
      );

      return {
        code: 200,
        message: 'success',
        data: {
          exists: !!existingUser
        }
      };
    }
  }
] as MockMethod[];
